import sys

from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *
from PySide6.QtCore import Qt, Signal, Slot,QSize
from PySide6.QtSql import QSqlDatabase
from PySide6.QtPrintSupport import QPrintDialog, QPrinter

from model.DataView import DataViewClass
from model.Save_DataView import SaveDataViewClass

from model.OutDataView import OutDataViewClass
from model.Out_Save_DataView import OutSaveDataViewClass

from PySide6.QtWebEngineWidgets import QWebEngineView
# from PySide6.QtGui import (QAction, QFont, QIcon, QKeySequence,
#                            QTextCharFormat, QTextCursor, QTextTableFormat)

import os
os.chdir(os.path.dirname(__file__))

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
      
        self.TabWidget = QTabWidget()
        self.Tabs = []
            
        self.setCentralWidget(self.TabWidget)
        
        self.create_actions()
        self.create_menus()
        self.create_tool_bars()
        self.create_status_bar()
        self.create_dock_windows()
        
        self.resize(1500, 800)
        self.setWindowTitle("文件管理平台")
        self.setWindowIcon(QIcon('images/bao12.png'))
        ##self.new_letter()
    
    def newTab(self, tab,tabname):
        self.TabWidget.addTab(tab, tabname)
        self.Tabs.append(tabname)
        button = QToolButton(self.TabWidget)
        button.setIcon(QPixmap('./images/close.png'))  # 确保你有这个图片文件
        button.setIconSize(QSize(16, 16))  # 设置图标大小
        # 设置无边框样式
        button.setStyleSheet("""
            QToolButton {
                border: none; /* 移除边框 */
                background-color: transparent; /* 如果需要，设置透明背景 */
            }
        """)
        button.clicked.connect(lambda: self.close_tab(self.Tabs.index(tabname)))

        # 将按钮添加到标签页的右上角
        self.TabWidget.tabBar().setTabButton(self.Tabs.index(tabname), QTabBar.RightSide, button)
        
    def close_tab(self, index):
        if index >= 0 and index < self.TabWidget.count():
            self.Tabs.remove(self.Tabs[index])
            self.TabWidget.removeTab(index)

    def new_letter(self):
        self._text_edit = QTextEdit()
        self._text_edit.clear()

        cursor = self._text_edit.textCursor()
        cursor.movePosition(QTextCursor.Start)
        bold_format = QTextCharFormat()
        bold_format.setFontWeight(QFont.Bold)

        table_format = QTextTableFormat()
        
        table_format.setBorder(1.5)
        table_format.setBorderStyle(QTextFrameFormat.BorderStyle_Solid)
        table_format.setCellPadding(16)
        table_format.setAlignment(Qt.AlignmentFlag.AlignCenter)
        

        cursor.insertImage(QImage('./images/bao12.png'))

    def print_(self):
        printer = QPrinter()
        print_dialog = QPrintDialog(printer, self)

        if print_dialog.exec_() == QDialog.Accepted:
            painter = QPainter(printer)  # 绑定 painter 到 printer
            image = QImage("./images/printMode.png")
            pixmap = QPixmap.fromImage(image)
            painter.drawPixmap(0, 0, pixmap)
            
            painter.setFont(QFont('Arial', 30))
            painter.drawText(200, 200, "标题")

            painter.end()  # 结束绘制，释放资源


            
    def save(self):
        dialog = QFileDialog(self, "Choose a file name")
        dialog.setMimeTypeFilters(['text/html'])
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        dialog.setDefaultSuffix('html')
        if dialog.exec() != QDialog.Accepted:
            return

        filename = dialog.selectedFiles()[0]
        file = QFile(filename)
        if not file.open(QFile.WriteOnly | QFile.Text):
            reason = file.errorString()
            QMessageBox.warning(self, "Dock Widgets",
                                "Cannot write file {filename}:\n{reason}.")
            return

        out = QTextStream(file)
        QApplication.setOverrideCursor(Qt.WaitCursor)
        out << self._text_edit.toHtml()
        QApplication.restoreOverrideCursor()

        self.statusBar().showMessage(f"Saved '{filename}'", 2000)

    def undo(self):
        document = self._text_edit.document()
        document.undo()

    def insert_customer(self, customer):
        if not customer:
            return
        customer_list = customer.split(', ')
        document = self._text_edit.document()
        cursor = document.find('NAME')
        if not cursor.isNull():
            cursor.beginEditBlock()
            cursor.insertText(customer_list[0])
            oldcursor = cursor
            cursor = document.find('ADDRESS')
            if not cursor.isNull():
                for i in customer_list[1:]:
                    cursor.insertBlock()
                    cursor.insertText(i)
                cursor.endEditBlock()
            else:
                oldcursor.endEditBlock()

    def add_paragraph(self, paragraph):
        if not paragraph:
            return
        document = self._text_edit.document()
        cursor = document.find("Yours sincerely,")
        if cursor.isNull():
            return
        cursor.beginEditBlock()
        cursor.movePosition(QTextCursor.PreviousBlock, QTextCursor.MoveAnchor,
                            2)
        cursor.insertBlock()
        cursor.insertText(paragraph)
        cursor.insertBlock()
        cursor.endEditBlock()

    def about(self):
        QMessageBox.about(self, "About Dock Widgets",
                          "The <b>Dock Widgets</b> example demonstrates how to use "
                          "Qt's dock widgets. You can enter your own text, click a "
                          "customer to add a customer name and address, and click "
                          "standard paragraphs to add them.")

    def create_actions(self):
        icon = QIcon.fromTheme('document-new', QIcon('images/new.png'))
        self._new_letter_act = QAction(icon, "&New Letter",
                                       self, shortcut=QKeySequence.New,
                                       statusTip="Create a new form letter", triggered=self.new_letter)

        icon = QIcon.fromTheme('document-save', QIcon('images/save.png'))
        self._save_act = QAction(icon, "&Save...", self,
                                 shortcut=QKeySequence.Save,
                                 statusTip="Save the current form letter", triggered=self.save)

        icon = QIcon.fromTheme('document-print', QIcon('images/printer.png'))
        self._print_act = QAction(icon, "&Print...", self,
                                  shortcut=QKeySequence.Print,
                                  statusTip="Print the current form letter",
                                  triggered=self.print_)

        icon = QIcon.fromTheme('edit-undo', QIcon('images/undo.png'))
        self._undo_act = QAction(icon, "&Undo", self,
                                 shortcut=QKeySequence.Undo,
                                 statusTip="Undo the last editing action", triggered=self.undo)

        self._quit_act = QAction("&Quit", self, shortcut="Ctrl+Q",
                                 statusTip="Quit the application", triggered=self.close)

        self._about_act = QAction("&About", self,
                                  statusTip="Show the application's About box",
                                  triggered=self.about)

        self._about_qt_act = QAction("About &Qt", self,
                                     statusTip="Show the Qt library's About box",
                                     triggered=QApplication.instance().aboutQt)

    def create_menus(self):
        self._file_menu = self.menuBar().addMenu("&File")
        self._file_menu.addAction(self._new_letter_act)
        self._file_menu.addAction(self._save_act)
        self._file_menu.addAction(self._print_act)
        self._file_menu.addSeparator()
        self._file_menu.addAction(self._quit_act)

        self._edit_menu = self.menuBar().addMenu("&Edit")
        self._edit_menu.addAction(self._undo_act)

        self._view_menu = self.menuBar().addMenu("&View")

        self.menuBar().addSeparator()

        self._help_menu = self.menuBar().addMenu("&Help")
        self._help_menu.addAction(self._about_act)
        self._help_menu.addAction(self._about_qt_act)

    def create_tool_bars(self):
        self._file_tool_bar = self.addToolBar("File")
        self._file_tool_bar.addAction(self._new_letter_act)
        self._file_tool_bar.addAction(self._save_act)
        self._file_tool_bar.addAction(self._print_act)

        self._edit_tool_bar = self.addToolBar("Edit")
        self._edit_tool_bar.addAction(self._undo_act)

    def create_status_bar(self):
        self.statusBar().showMessage("Ready")

    def create_dock_windows(self):
        dock = QDockWidget("收文", self)
        dock.setAllowedAreas(Qt.LeftDockWidgetArea)
        self._customer_list = QListWidget(dock)
        self._customer_list.addItems((
            "收文目录",
            "归档收文",
            "文件库"))
        dock.setWidget(self._customer_list)
        self.addDockWidget(Qt.LeftDockWidgetArea, dock)
        self._view_menu.addAction(dock.toggleViewAction())

        dock = QDockWidget("发文", self)
        self._paragraphs_list = QListWidget(dock)
        self._paragraphs_list.addItems((
            "发文目录",
            "归档发文"))
        dock.setWidget(self._paragraphs_list)
        self.addDockWidget(Qt.LeftDockWidgetArea, dock)
        self._view_menu.addAction(dock.toggleViewAction())

        self._customer_list.currentTextChanged.connect(lambda item: self.run_customer_item(item))
        self._paragraphs_list.currentTextChanged.connect(lambda item: self.run_paragraphs_item(item))
        
    def run_customer_item(self, item):
        if item == "收文目录":
            if '收文目录' not in self.Tabs:
                self.mySqlQueryMode = DataViewClass()
                self.newTab(self.mySqlQueryMode, '收文目录')
            self.TabWidget.setCurrentIndex(self.Tabs.index('收文目录'))
        elif item == "归档收文":
            if '归档收文' not in self.Tabs:
                self.mySqlQueryMode = SaveDataViewClass()
                self.newTab(self.mySqlQueryMode, '归档收文')
            self.TabWidget.setCurrentIndex(self.Tabs.index('归档收文'))

    def run_paragraphs_item(self, item):
        if item == "发文目录":
            if '发文目录' not in self.Tabs:
                self.mySqlQueryMode = OutDataViewClass()
                self.newTab(self.mySqlQueryMode, '发文目录')
            self.TabWidget.setCurrentIndex(self.Tabs.index('发文目录'))
        elif item == "归档发文":
            if '归档发文' not in self.Tabs:
                self.mySqlQueryMode = OutSaveDataViewClass()
                self.newTab(self.mySqlQueryMode, '归档发文')
            self.TabWidget.setCurrentIndex(self.Tabs.index('归档发文'))

if __name__ == '__main__':

    app = QApplication(sys.argv)

    # 打开数据库，该库由qt_createSql.py脚本创建。
    db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName('./db/filedatabase.db')
    if db.open() is not True:
        QMessageBox.critical(QWidget, 'open error', '数据库打开失败')
        exit()
    main_win = MainWindow()
    main_win.show()
    sys.exit(app.exec())
